﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Revit;
using YJKBatchPrinter.Layout;

namespace YJKBatchPrinter.Commands
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdLayout : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			Document document = cmdData.Application.ActiveUIDocument.Document;
			List<Element> elementByCategory = YJKElementFilter.GetElementByCategory(document, BuiltInCategory.OST_Views);
			List<Element> listView = new List<Element>();
			this.FilteringAlreadyExistingDrawing(document, elementByCategory, ref listView);
			List<Element> elementByCategory2 = YJKElementFilter.GetElementByCategory(document, BuiltInCategory.OST_Sheets);
			LayoutForm layoutForm = new LayoutForm(cmdData, listView, elementByCategory2);
			layoutForm.ShowDialog();
			if (CmdLayout.ResultType.RT_PRINTER == layoutForm.m_rt)
			{
				PrinterFunctionManager.Printting(cmdData);
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void FilteringAlreadyExistingDrawing(Autodesk.Revit.DB.Document doc, List<Element> listView, ref List<Element> listOutView)
		{
			foreach (Element element in listView)
			{
				Autodesk.Revit.DB.View view = (Autodesk.Revit.DB.View)element;
				if (view != null && !view.IsTemplate && ((int)view.ViewType == 1 || (int)view.ViewType == 2 || (int)view.ViewType == 10 || (int)view.ViewType == 117 || (int)view.ViewType == 4 || (int)view.ViewType == 3))
				{
					Parameter parameter = view.GetParameter(BuiltInParameter.VIEWPORT_SHEET_NUMBER);
					if (parameter == null || !(parameter.AsString() != "") || parameter.AsString() == null)
					{
						listOutView.Add(view);
					}
				}
			}
		}

		private bool HasElementByView(Autodesk.Revit.DB.Document doc, Autodesk.Revit.DB.View view)
		{
			IList<Element> list = new FilteredElementCollector(doc, view.Id).ToElements();
			if (list.Count == 0)
			{
				return false;
			}
			foreach (Element element in list)
			{
				if ((element.Category != null || !(element.Name == "ExtentElem")) && (element.Category == null || element.Category.Id.IntegerValue != -2000500))
				{
					return true;
				}
			}
			return false;
		}

		public enum ResultType
		{
			RT_OK,
			RT_PRINTER
		}
	}
}
